<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <room-message :list="list" />
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImg"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, nextTick, provide } from 'vue'
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums/index'
import { getConsultOrderDetail } from '@/api/consult'

let list = ref<Message>([])
let socket: Socket

const store = useUserStore()

const route = useRoute()

const initSocket = () => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user.token}`,
    },
    query: {
      orderId: route.query.orderId,
    },
  })
  socket.on('connect', () => {
    console.log('浏览器和WS服务器建立连接成功!')
  })
  socket.on('error', (error: any) => {
    console.log('出错了!', error)
  })
  socket.on('disconnect', () => {
    console.log('浏览器和WS服务器建立断开连接!')
  })

  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log('建立连接后,返回的默认数据:', data)
    const result: Message[] = []
    data.forEach((item) => {
      result.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: {
          content: item.createTime,
        },
      })
      result.push(...item.items)
    })
    list.value.push(...result)
    console.log(list.value)
  })

  socket.on('receiveChatMsg', async (msg: any) => {
    list.value.push(msg)

    await nextTick()

    window.scrollTo(0, document.body.scrollHeight)
  })

  socket.on('statusChange', () => {
    getOrderDetail()
    console.log('订单更新了!')
  })
}

const consult = ref<ConsultOrderItem>()
const getOrderDetail = async () => {
  const { data } = await getConsultOrderDetail(route.query.orderId as string)
  console.log('订单详情', data)
  consult.value = data
}

onMounted(() => {
  initSocket(), getOrderDetail()
})

const sendText = (text: string) => {
  console.log('文字消息内容', text)
  socket.emit('sendChatMsg', {
    from: store.user.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text,
    },
  })
}

const sendImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img,
    },
  })
}

//===异步数据一定要注入响应式的===
//问题:注入的时候consult.value不是响应式=》 需要注入consult响应式
provide('consult', consult)

const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
onUnmounted(() => {
  socket.close()
})
</script>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
